<?php
/**
 * 公共函数库，不依赖于框架 tool.php
 * Author: 勾国印 (phper@gouguoyin.cn)
 * Date: 2015年12月8日 下午10:17:30
 */

/**
 * curl模拟http请求，支持get和
 * @param string $url 请求的地址
 * @param string $type get/post,不区分大小写
 * @param array/string/json $data 要传输的数据，支持字符串、数组和json格式
 * @param string $content_type 设置header格式
 * @param int $timeout 超时时间
 */

function http_request($url, $type = 'get', $data = null, $content_type = 'application/json', $time_out = 20){
    $curl = curl_init();
    $type = strtoupper($type);


    if (!in_array($type, array('POST','GET'))) {
        $error_array = array(
            'error_no' => '-1',
            'error_msg' => '非法的请求方式'
        );
        return json_encode($error_array);
    }

    if ($data) {
        if ($type == 'POST') {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        } else if ($type == 'GET') {
            $data = http_build_query($data);
            $url = strpos($url, '?') !== false ? $url.'&'.$data :  $url.'?'.$data;
        }
    }

    $headers = array(
        "Content-type: $content_type",
        "Cache-Control: no-cache",
    );

    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_TIMEOUT,$time_out);
    $output     = curl_exec($curl);
    $curl_no    = curl_errno($curl);
    $curl_error = curl_error($curl);
    $curl_info  = curl_getinfo($curl);
    curl_close($curl);

    if ($curl_no > 0) {
        $error_array = array(
            'error_no' => $curl_no,
            'error_msg' => $curl_error
        );
        return json_encode($error_array);
    }

    //print_r($curl_info);exit;

    $http_code = $curl_info['http_code'];

    if ('200' != $http_code) {
        $error_array = array(
            'error_no' => $http_code,
            'error_msg' => 'URL请求错误，HTTP状态码为'.$http_code
        );
        return json_encode($error_array);
    }
    return $output;
}

/**
 * 显示距离当前时间的字符串
 * @param string $time 格式化时间,如2016-06-25
 * @return string
 */

function time_past($time)
{
    $now        = time();
    $time_past  = $now - strtotime($time);

    // 如果小于1分钟（60s），则显示"刚刚"
    if ($time_past < 60) {
        return '刚刚';
    }

    $time_mapping = array(
        '分钟' => '60',
        '小时' => '24',
        '天'   => '7',
        '周'   => '4',
        '月'   => '12',
        '年'   => '100'
    );

    $time_past = floor($time_past / 60);

    foreach($time_mapping as $k=>$v) {
        if ($time_past < $v) {
            return floor($time_past).$k.'前';
        }
        $time_past = $time_past / $v;
    }

    // 如果小于1小时（60*60s），则显示N分钟前
    // 如果小于24个小时（60*60*24s），则显示N小时前
    // 如果大于24个小时（60*60*24s），则显示N天前
}

/**
 * 随机产生A-Z, a-z, 0-9的字符串
 * @param int $length 随机数的长度
 * @return string
 */
function random_hash($length = 4)
{
    $salt = array_merge(range('A', 'Z'), range('a', 'z'), range(0, 9));
    $count = count($salt);
    $hash = '';
    for ($i = 0; $i < $length; $i++) {
        $hash .= $salt[mt_rand(0, $count-1)];
    }
    return $hash;
}


/**
 * 截取字符串
 * @param string $str 所要截取的字符串
 * * @param number $len 所要截取长度
 * @return string 返回截取后的字符串
 */
function cut_str($str, $len, $fix = '...')
{
    $str = trim($str);
    $str_len = mb_strlen($str , 'UTF-8');
    $new_str = mb_substr($str, 0, $len, 'UTF-8');
    if ($str_len > $len) {
        return $new_str.$fix;
    } else {
        return $str;
    }
}

//aes加密
function aes_encrypt($str)
{
    $key = "ShowMe\$The\$Money";

    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
        $str, MCRYPT_MODE_ECB,null);

    return base64_encode($ciphertext);
}

//aes解密
function aes_descrypt($str)
{
    $key = "ShowMe\$The\$Money";
    $ciphertext_dec = base64_decode($str);
    //$iv_dec         = substr($ciphertext_dec, 0, null);
    //$ciphertext_dec = substr($ciphertext_dec, null);

    return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
        $ciphertext_dec, MCRYPT_MODE_ECB, null);
}

// 密码加密
function password_encrypt($password)
{
    return md5(aes_encrypt($password));
}

//id加密
function id_encrypt($id, $length = 10)
{
    if(!is_numeric($id)){
        return ;
    }
    $XDeode = new \Common\Lib\XDeode($length);
    return $XDeode->encode($id);
}

//id解密
function id_descrypt($str)
{
    $XDeode = new \Common\Lib\XDeode();
    return $XDeode->decode($str);
}


